package xingkong.core;

import java.util.Date;
import java.util.List;

import com.alibaba.druid.util.StringUtils;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import xingkong.tools.MD5Util;
import xingkong.tools.ResponseContent;
import xingkong.tools.StaticFields;

public class UserController extends Controller{
	
	public void index() throws Exception{
//		List<Record> list = Db.find("select * from tb_user");
//		renderJson(list);
		Record user = (Record)(getSession().getAttribute(StaticFields.CURRENTUSER));
		if(null != user){
			Record record = Db.findFirst("SELECT `id`,`integral` FROM `xingkong`.`tb_integral` i where i.user_id=?",user.getStr("id"));
			int integral = 0;
			if(null != record){
				integral = record.get("integral");
			}
			user.set("integral", integral);
			getSession().setAttribute(StaticFields.CURRENTUSER, user);
		}
		renderJsp("/WEB-INF/content/index.jsp");
	}
	
	public void tologin(){
		renderJsp("/WEB-INF/content/login.jsp");
	}
	
//	public void tologin2(){
//		renderJsp("/WEB-INF/content/login2.jsp");
//	}
	
	public void toforget(){
		renderJsp("/WEB-INF/content/forget.jsp");
	}
	
	public void toreg(){
		renderJsp("/WEB-INF/content/reg.jsp");
	}
	
	public void addAccount(){
		System.out.print("批量注册");
		renderJson(new ResponseContent(StaticFields.CORRECT, "操作成功！", null));
	}
	
	
	/**
	 * 到管理员注册页面
	 */
	public void admin(){
		renderJsp("/WEB-INF/content/regAdmin.jsp");
	}
	/**
	 * 批量注册
	 */
	public void toregs(){
		renderJsp("/WEB-INF/content/regs.jsp");
	}
	
	/**
	 * 登陆
	 * 登陆成功返回 积分
	 */
	public void login()  throws Exception{
		String loginName = getPara("login_name");
		String password = getPara("password");
		if (StringUtils.isEmpty(loginName)) {
			renderJson(new ResponseContent(StaticFields.WRONG, "用户名不能为空", null));
			return;
		}
		if(StringUtils.isEmpty(password)){
			renderJson(new ResponseContent(StaticFields.WRONG, "用户名不能为空", null));
			return;
		}
		List<Record> users = Db.find("select id,login_name,type from tb_user u where u.login_name=? and u.password=?",loginName,MD5Util.md5(password));
//		List<Record> users = Db.find("select id,login_name,type from tb_user u where u.login_name=? and u.password=?",loginName,password);
		if (users.isEmpty()) {
			renderJson(new ResponseContent(StaticFields.WRONG, "用户名或者密码不正确！", null));
			return;
		}
		if(users.size()>1){
			renderJson(new ResponseContent(StaticFields.WRONG, "数据错误，请联系管理员", null));
			return;
		}
		Record user = users.get(0);
//		System.out.println(user.getStr("id"));
		Record record = Db.findFirst("SELECT `id`,`integral` FROM `xingkong`.`tb_integral` i where i.user_id=?",user.getStr("id"));
		int integral = 0;
		if(null != record){
			integral = record.get("integral");
		}
		getSession().setAttribute(StaticFields.CURRENTUSER, users.get(0).set("integral", integral));
		renderJson(new ResponseContent(StaticFields.CORRECT, "登陆成功！", null));
	}
	/**
	 * 注销
	 */
	public void logout(){
		getSession().invalidate();
		getSession().removeAttribute(StaticFields.CURRENTUSER);
		getRequest().getSession().invalidate();
		getRequest().getSession().removeAttribute(StaticFields.CURRENTUSER);
		redirect("/user/tologin");
	}
	
	/**
	 * 注册
	 */
	@Before(Tx.class)
	public void reg() throws Exception{
		String loginName = getPara("login_name");
		String password = getPara("password");
		String pwdtips = getPara("pwdtips");
		String type = getPara("type");//
		if (StringUtils.isEmpty(loginName)) {
			renderJson(new ResponseContent(StaticFields.WRONG, "用户名不能为空", null));
			return;
		}
		if(StringUtils.isEmpty(password)){
			renderJson(new ResponseContent(StaticFields.WRONG, "密码不能为空", null));
			return;
		}
		if(StringUtils.isEmpty(pwdtips)){
			renderJson(new ResponseContent(StaticFields.WRONG, "密码提示不能为空", null));
			return;
		}
		if(this.isExist(loginName)){
			renderJson(new ResponseContent(StaticFields.WRONG, "用户已存在", null));
			return;
		}
		Date date = new Date();
		if(!StringUtils.isEmpty(type) && "1".equals(type)){
			//添加管理员
			if(this.checkAdminExist()){
				renderJson(new ResponseContent(StaticFields.WRONG, "管理员已存在", null));
				return;
			}
			Record record = new Record().set("login_name", loginName).set("password", MD5Util.md5(password)).set("register_time", date).set("type", "1").set("pwdtips", pwdtips);
			boolean f = Db.save("tb_user", record);
		}else{
			Record record = new Record().set("login_name", loginName).set("password", MD5Util.md5(password)).set("register_time", date).set("type", "2").set("pwdtips", pwdtips);
			boolean f = Db.save("tb_user", record);
			if(!f){
				renderJson(new ResponseContent(StaticFields.WRONG, "服务器异常", null));
				return;
			}
			boolean f2 = Db.save("tb_integral", new Record().set("integral", StaticFields.DEFAULT).set("create_time", date).set("user_id", record.get("id")));
			if(!f2){
				//renderJson(new ResponseContent(StaticFields.WRONG, "服务器异常", null));
				throw new Exception();
			}
		}
		renderJson(new ResponseContent(StaticFields.CORRECT, "注册成功！", null));
	}
	/**
	 * 验证当前注册用户名是否存在
	 * @param loginName 注册用户名
	 * @return true 存在 false 不存在
	 */
	private boolean isExist(String loginName)  throws Exception{
		return Db.queryLong("select count(1) from tb_user u where u.login_name=?",loginName) > 0;
	}
	/**
	 * 验证是否是当前用户忘记密码
	 * @param loginName 用户名
	 * @param pwdtips 密码提示
	 * @return true：是 false 否
	 * @throws Exception
	 */
	private boolean checkPwdtips(String loginName,String pwdtips)throws Exception{
		return Db.queryLong("select count(1) from tb_user u where u.login_name = ? and u.pwdtips = ?",loginName,pwdtips)>0;
	}
	/**
	 * 验证管理员是否存在
	 * @return true 存在 false 不存在
	 * @throws Exception
	 */
	private boolean checkAdminExist()throws Exception{
		return Db.queryLong("select count(1) from tb_user u where u.type='0'")>0;
	}
	/**
	 * 修改密码
	 */
	public void editPassword()  throws Exception{
		String loginName = getPara("login_name");
		String password = getPara("password");
		String repassword = getPara("repassword");
		String pwdtips = getPara("pwdtips");
		if (StringUtils.isEmpty(loginName)) {
			renderJson(new ResponseContent(StaticFields.WRONG, "用户名不能为空", null));
			return;
		}
		if(StringUtils.isEmpty(password)){
			renderJson(new ResponseContent(StaticFields.WRONG, "密码不能为空", null));
			return;
		}
		if(StringUtils.isEmpty(repassword)){
			renderJson(new ResponseContent(StaticFields.WRONG, "重复密码不能为空", null));
			return;
		}
		if(password.equals(repassword)){
			renderJson(new ResponseContent(StaticFields.WRONG, "两次密码不一样", null));
			return;
		}
		if(!this.isExist(loginName)){
			renderJson(new ResponseContent(StaticFields.WRONG, "该用户不存在", null));
			return;
		}
		if(!this.checkPwdtips(loginName, pwdtips)){
			renderJson(new ResponseContent(StaticFields.WRONG, "密码提示不正确，请联系管理员", null));
			return;
		}
		int i = Db.update("update tb_user set password = ? where login_name = ? and pwdtips = ?",MD5Util.md5(password),loginName,pwdtips);
		if(i!=1){
			renderJson(new ResponseContent(StaticFields.WRONG, "密码修改出错", null));
			return;
		}
		renderJson(new ResponseContent(StaticFields.CORRECT, "密码修改成功！", null));
	}
	
//	public void addBankMD5(){
//		List<Record> list = MD5Util.bankMD5();
//		int[] i = Db.batchSave("tb_md5_bank", list, list.size());
//		System.out.println(i);
//		renderJson(new ResponseContent(StaticFields.CORRECT, "密码修改成功！", i));
//	}
//	
//	public void list(){
//		List<Record> list = Db.find("select * from tb_user");
//		long count = Db.queryLong("select count(1) count from tb_user");
////		renderJson("code":);
//		renderJson(new LayuiResponseContent("",count,list));
//	}
}
